import React from 'react'
import './index.less'

// 饼图数据类型
type PieType = 'success' | 'warning' | 'error'
interface PieData {
  type: PieType
  value: number
  label: string
  color: string
}

interface ProcessPieProps {
  data: PieData[]
  total: number
  title?: string
}

function getPercent(val: number, total: number) {
  if (total === 0) return '0%'
  // 保留两位小数并避免精度问题
  const percent = (val / total) * 100
  return percent.toFixed(2).replace(/\.00$/, '') + '%'
}

const SVG_SIZE = 200
const RADIUS = 75
const CENTER = 100

const ProcessPie: React.FC<ProcessPieProps> = ({ data, total: _total, title }) => {
  // 统一用 data 的 value 求和作为 total
  const total = data.reduce((sum, d) => sum + d.value, 0)

  // 全部为0时，显示暂无数据
  if (total === 0) {
    return (
      <div className="process-pie-container">
        <div className="process-pie-title">{title || '生产进度异常情况'}</div>
        <div className="process-pie-main" style={{ justifyContent: 'center', alignItems: 'center', minHeight: 200 }}>
          <div style={{ color: '#999', fontSize: 16, textAlign: 'center', width: '100%' }}>暂无数据</div>
        </div>
      </div>
    )
  }

  // 计算每个扇区的起止角度
  let startAngle = 0
  const sectors = data.map((d) => {
    const angle = (d.value / total) * 360
    const sector = { ...d, startAngle, endAngle: startAngle + angle }
    startAngle += angle
    return sector
  })

  // 生成饼图扇区 path
  function describeSector(cx: number, cy: number, r: number, startAngle: number, endAngle: number) {
    const start = polarToCartesian(cx, cy, r, endAngle)
    const end = polarToCartesian(cx, cy, r, startAngle)
    const largeArcFlag = endAngle - startAngle > 180 ? 1 : 0
    return [`M ${cx} ${cy}`, `L ${start.x} ${start.y}`, `A ${r} ${r} 0 ${largeArcFlag} 0 ${end.x} ${end.y}`, 'Z'].join(
      ' ',
    )
  }

  function polarToCartesian(cx: number, cy: number, r: number, angle: number) {
    const rad = (angle - 90) * (Math.PI / 180)
    return {
      x: cx + r * Math.cos(rad),
      y: cy + r * Math.sin(rad),
    }
  }

  // 百分比文本坐标（扇区中点，偏内侧）
  function getLabelPos(s: (typeof sectors)[0]) {
    const midAngle = (s.startAngle + s.endAngle) / 2
    const rad = (midAngle - 90) * (Math.PI / 180)
    return {
      x: CENTER + RADIUS * 0.6 * Math.cos(rad),
      y: CENTER + RADIUS * 0.6 * Math.sin(rad),
    }
  }

  // 只有一个有值时，渲染满圆
  const nonZeroSectors = sectors.filter((s) => s.value > 0)
  if (nonZeroSectors.length === 1) {
    const s = nonZeroSectors[0]
    return (
      <div className="process-pie-container">
        <div className="process-pie-title">{title || '生产进度异常情况'}</div>
        <div className="process-pie-main">
          <div className="process-pie-chart" style={{ width: SVG_SIZE, height: SVG_SIZE }}>
            <svg width={SVG_SIZE} height={SVG_SIZE}>
              <circle cx={CENTER} cy={CENTER} r={RADIUS} fill={s.color} />
              <text
                x={CENTER}
                y={CENTER}
                fontSize="14"
                fontWeight="bold"
                fill="#111"
                textAnchor="middle"
                dominantBaseline="middle"
              >
                {getPercent(s.value, total)}
              </text>
            </svg>
          </div>
          {/* 右侧图例和总计照常渲染 */}
          <div className="process-pie-stats">
            {data.map((d) => (
              <div className="process-pie-stat-item" key={d.type}>
                <div className="process-pie-stat-item-top">
                  <div className="process-pie-block-color" style={{ backgroundColor: d.color }} />
                  <div className="process-pie-value">{d.value}</div>
                </div>
                <div className="process-pie-label">{d.label}</div>
              </div>
            ))}
          </div>
          <div className="process-pie-total">总计 {total} 条</div>
        </div>
      </div>
    )
  }

  return (
    <div className="process-pie-container">
      <div className="process-pie-title">{title || '生产进度异常情况'}</div>
      <div className="process-pie-main">
        <div className="process-pie-chart" style={{ width: SVG_SIZE, height: SVG_SIZE }}>
          <svg width={SVG_SIZE} height={SVG_SIZE}>
            {/* 饼图扇区 */}
            {sectors.map((s) => (
              <path key={s.type} d={describeSector(CENTER, CENTER, RADIUS, s.startAngle, s.endAngle)} fill={s.color} />
            ))}
            {/* 百分比文本 */}
            {sectors.map((s) => {
              const { x, y } = getLabelPos(s)
              return s?.value ? (
                <text
                  key={s.type + '-percent'}
                  x={x}
                  y={y}
                  fontSize="14"
                  fontWeight="bold"
                  fill="#111"
                  textAnchor="middle"
                  dominantBaseline="middle"
                >
                  {getPercent(s.value, total)}
                </text>
              ) : null
            })}
          </svg>
        </div>
        {/* 右侧图例 */}
        <div className="process-pie-stats">
          {data.map((d) => (
            <div className="process-pie-stat-item" key={d.type}>
              <div className="process-pie-stat-item-top">
                <div className="process-pie-block-color" style={{ backgroundColor: d.color }} />
                <div className="process-pie-value">{d.value}</div>
              </div>
              <div className="process-pie-label">{d.label}</div>
            </div>
          ))}
        </div>

        <div className="process-pie-total">总计 {total} 条</div>
      </div>
    </div>
  )
}

export default ProcessPie
